﻿using System;

class BinarySearch
{
    static void Main()
    {
        int[] array = { -3, -1, 0, 5, 12, 15, 24, 46, 67, 345, 349, 678, 999, 1012, 1456, 1457, 1458, 436678, 9234567 };
        int minIndex = 0;
        int maxIndex = array.Length - 1;
        int target = 999;

        for (int i = 0; i < array.Length; i++)
        {
            Console.WriteLine("[{0}] --> {1}", i, array[i]);
        }

        Console.WriteLine();

        int result = MyBinarySearch(array, minIndex, maxIndex, target);

        if (result != -1)
        {
            Console.WriteLine("The target value ({0}) has index: [{1}]", target, result);
        }
        else
        {
            Console.WriteLine("The target value ({0}) is not found!", target);
        }
    }

    public static int MyBinarySearch(int[] arr, int min, int max, int key)
    {
        while (max >= min)
        {
            int mid = (min + max) / 2;

            if (arr[mid] < key)
            {
                min = mid + 1;
            }
            else if (arr[mid] > key)
            {
                max = mid - 1;
            }
            else
            {
                return mid;
            }
        }

        return -1;
    }
}